package com.gzhryc.shared_device.oem.micro.queue.work;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrder;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.oem.code.HttpNetworkServiceUtils;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.event.OrderCancelEvent;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderService;

import java.util.Date;
import java.util.List;

public class CDCZCacheFinishCheckRunnable implements Runnable{

    static Logger log = Logger.getLogger(CDCZCacheFinishCheckRunnable.class);

    OperateInfo operateInfo;

    public CDCZCacheFinishCheckRunnable(OperateInfo operateInfo){
        this.operateInfo = operateInfo;
    }

    @Override
    public void run() {
        try {
            List<CDCZOrder> deviceOrderList = RedisCacheManager.findWorkingCDCZDeviceOrder();
            if(deviceOrderList != null && deviceOrderList.size() > 0) {
                for (CDCZOrder deviceOrder : deviceOrderList) {
                    if (deviceOrder.getEndDate() == null) {
                        log.error("{{0}}充电插座订单无结束时间，订单状态为：{{1}}，强制撤销处理", deviceOrder.getTradeNo(), deviceOrder.getStateName());
                        try {
                            //清理缓存，避免定时器重复处理
                            RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());
                            //从数据库获取设备订单信息，避免缓存脏数据
                            deviceOrder = CDCZOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                            ICDCZNetworkService networkService = HttpNetworkServiceUtils.getCDCZNetworkService(deviceOrder.getIotId());
                            operateInfo.setOperateNote("订单启动失败");

                            Date cancelDate = new Date();
                            Long incomeMoney = deviceOrder.getIncomeMoney();

                            int cancelResult = CDCZOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder, PayServiceFactory.self(), networkService, operateInfo);
                            if (cancelResult > 0) {
                                //清理缓存，避免定时器重复处理
                                RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());
                                if (cancelResult == 2) {
                                    deviceOrder = CDCZOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                    //同步会员订单
                                    MemberBusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(), deviceOrder.getMoney()
                                            ,deviceOrder.getPayMoney(),deviceOrder.getWalletMoney());
                                    BusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(),cancelDate);
                                    JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                                    if (producer != null) {
                                        OrderCancelEvent event = new OrderCancelEvent(EDeviceFunCode.CDCZ.index(), deviceOrder.getTradeNo()
                                                ,deviceOrder.getCreateDate(),incomeMoney,cancelDate);
                                        KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,KafkaEventConstants.KEY_OrderCancel, JsonTools.toJson(event));
                                        producer.send(kafkaMessage);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    } else {
                        try {
                            Long times = DateTools.differenceMinute(new Date(), deviceOrder.getEndDate());
                            if (times <= 0) {
                                //清理缓存，避免定时器重复处理
                                RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());
                                //从数据库获取设备订单信息，避免缓存脏数据
                                deviceOrder = CDCZOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                Long payMoney = PlaceBusinessConfigService.self().getCDCZPayMoney(deviceOrder.getPlaceId(), deviceOrder.getMaxUsePower());
                                ICDCZNetworkService networkService = HttpNetworkServiceUtils.getCDCZNetworkService(deviceOrder.getIotId());
                                operateInfo.setOperateNote("订单到时完成");
                                if (CDCZOrderService.self(deviceOrder.getCreateDate()).timesFillToFinish(deviceOrder, payMoney, networkService, operateInfo)) {
                                    deviceOrder = CDCZOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                    //同步会员订单
                                    MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(),deviceOrder.getMoney(),
                                            deviceOrder.getPayMoney(), deviceOrder.getWalletMoney());
                                    JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                                    if (producer != null) {
                                        OrderFinishEvent event = new OrderFinishEvent(EBusinessType.CDCZ.index(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate(),operateInfo);
                                        KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
                                        producer.send(kafkaMessage);
                                    }
                                } else {
                                    log.error("完成充电插座订单失败，订单信息：{{0:json}}", deviceOrder);
                                }
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
